﻿/*文件注释
 * ===============================================================================
 * 说明：构建url
 * 
 * 作者：曾永佑
 * 版本：V1.0
 * 创建日期：2013-05-12
 * 完成日期： 
 * 修改纪录：  
 * ===============================================================================
 */  
        
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized; 

namespace SRF.UI
{
    public class UrlBuilder
    {
        string path;
        StringDictionary paras;

        public UrlBuilder(string url)
        {
            paras = new StringDictionary();
            string paraString;
            int p = url.IndexOf('?');
            if (p > -1)
            {
                path = url.Substring(0, p);
                paraString = url.Substring(p + 1);
            }
            else
            {
                path = url;
                paraString = "";
            }
            foreach (string para in paraString.Split('&'))
            {
                int ep = para.IndexOf('=');
                if (ep > -1)
                {
                    paras.Add(para.Substring(0, ep), para.Substring(ep + 1));
                }
            }
        }
        public UrlBuilder(System.Web.HttpRequestBase request)
        {
            path=string.Format("{0}://{1}{2}",request.Url.Scheme,request.Url.Authority,request.Url.AbsolutePath);
            paras=new StringDictionary();
            for(int i=0;i<request.QueryString.Count;i++)
            {
                paras.Add(request.QueryString.Keys[i],request.QueryString[i]);
            }
        }

        public UrlBuilder Append(string key, string value)
        {
            paras[key] = value; 

            return this;
        }
        public UrlBuilder Remove(string key)
        {
            if (Contains(key))
            {
                paras.Remove(key);
            }

            return this;
        }
        public bool Contains(string key)
        {
            return paras.ContainsKey(key);
        }
        public string this[string key]
        {
            get
            {
                return paras[key];
            }
            set
            {
                paras[key] = value;
            }
        }

        public static implicit operator UrlBuilder(string url)
        {
            return new UrlBuilder(url);
        } 

        public override string ToString()
        {
            StringBuilder paraSring = new StringBuilder();
            foreach (string key in this.paras.Keys)
            {
                paraSring.AppendFormat("&{0}={1}", key, this.paras[key]);
            }
            if (paraSring.Length > 0)
                return path += "?" + paraSring.ToString().TrimStart('&');
            else
                return path;
        }
    }
}